<template>
  <div>
    <h2 v-if="firstView">输入用户名搜索</h2>
    <h2 v-if="loading">LOADING.....</h2>
    <h2 v-if="errorMsg">{{ errorMsg }}</h2>
    <div class="row">
    <div class="card" v-for="(user,index) in users" :key="index">
      <a :href="user.url" target="_blank">
        <img :src="user.avatarUrl" style='width: 100px'/>
      </a>
      <p class="card-text">{{ user.name }}</p>
    </div>
  </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import axios from 'axios'
export default {
  name: 'Main',
  data () {
    return {
      firstView: true,
      loading: false,
      users: null,
      errorMsg: ''
    }
  },
  mounted () {
    PubSub.subscribe('search', (message, searchName) => {
      this.firstView = false
      this.loading = true
      this.users = []
      this.errorMsg = ''
      // 发ajax请求进行搜索
      const url = `https://api.github.com/search/users?q=${searchName}`
      axios.get(url).then(response => {
        this.loading = false
        // map() 方法返回一个新数组，不会改变原始数组。
        // 同时新数组中的元素为原始数组元素调用函数处理后的值，并按照原始数组元素顺序依次处理元素。
        // 注意：map() 不会对空数组进行检测。
        this.users = response.data.items.map(item => ({
          url: item.html_url,
          avatarUrl: item.avatar_url,
          username: item.login
        }))
      }).catch(error => {
        this.loading = false
        this.errorMsg = '请求失败'
        console.log(error)
      })
    })
  }
}
</script>

<style scoped>
.card {
  float: left;
  width: 33.333%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: .75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>
